import {
	apiMixUrlApi
} from '@/api/assemb.js';

function download(file, type) {
	let URl = file.audioUrl
	if (URl.indexOf('https') >= 0) {
		pchome(URl, file, type)
	} else {
		let prams = {
			files: [URl]
		};
		apiMixUrlApi(prams, 1003, 'uploadFileToOss').then(json => {
			let oss = result.ossUrl;
			pchome(oss[0], file, type)
		});
	}
}

function pchome(URl, file, type) {
	const downloadTask = uni.downloadFile({
		url: URl,
		success: (res) => {
			if (res.statusCode === 200) {
				uni.hideLoading();
				console.log('下载成功', res);
				switch (type) {
					case 'saveAlbum':
						saveAlbum(res)
						break;
					case 'exportToWeChat':
						exportToWeChat(res, file)
						break;
					default:
						break;
				}
			}
		},
		complete: () => {
			uni.hideLoading();
		}
	});
	downloadTask.onProgressUpdate((res) => {
		uni.showLoading({
			title: '下载' + res.progress + '%'
		});
		/* console.log('下载进度' + res.progress);
		console.log('已经下载的数据长度' + res.totalBytesWritten);
		console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
		// 满足测试条件，取消下载任务。
		if (res.progress > 50) {
			downloadTask.abort();
		} */
	});
}

function exportToWeChat(res, file) {
	console.log(res.tempFilePath, "导出至微信");
	let houzhui = file.audioUrl.match(/\.[^.]+?$/)[0];
	wx.shareFileMessage({
		filePath: res.tempFilePath,
		fileName: file.audioName + houzhui,
		success() {},
		fail: console.error
	});
}

function saveAlbum(res) {
	uni.saveVideoToPhotosAlbum({
		filePath: res.tempFilePath,
		success: function() {
			uni.showToast({
				title: '保存成功！',
				icon: 'success',
				duration: 2000
			});
		},
		fail: function() {
			uni.showToast({
				title: '保存失败！',
				icon: 'error',
				duration: 2000
			});
		}
	});
}

export {
	download
}
